/*
 * @Author: 周凯
 * @Date: 2020-10-20 09:35:40
 * @LastEditTime: 2020-10-21 09:59:21
 */
// const ipcamera = require("../node-dahua-api/dahua");
const ipcamera = require("node-dahua-api-zhoukai");
const express = require("express");
const app = express();
const router = express.Router();
const dayjs = require("dayjs");

const port = 9090;
// Options:
const options = {
  host: "192.168.32.241",
  port: "80",
  user: "admin",
  pass: "a12345678",
  log: true,
};
const json = {
  data: {},
  time: dayjs(Date.now(), "YYYY-MM-DD HH:mm:ss"),
  code: 0,
};
let dahua;
// let dahua = new ipcamera.dahua(options);

router.get("/", (req, res) => {
  res.send("成功了");
  res.status(200);
});

router.get("/init", (req, res) => {
  const query = req.query;

  if (!query.host || !query.user || !query.pass) {
    ErrorMsg(res, "请查看host,user,pass是否填写");
    return;
  }
  dahua = new ipcamera.dahua(
    Object.assign(options, {
      host: query.host,
      user: query.user,
      pass: query.pass,
    })
  );
  SuccMsg(res, "初始化成功");
});
router.get("/ptz", async (req, res) => {
  const query = req.query;
  if (query.status && dahua) {
    switch (query.status) {
      // PTZ Move
      // Directions = Up/Down/Left/Right/LeftUp/RightUp/LeftDown/RightDown
      // Actions = start/stop
      // Speed = 1-8
      // 移动摄像头
      case "ptzMove":
        try {
          await PtzMove(query);
          SuccMsg(res, `操作${query.actions}成功`);
        } catch (err) {
          ErrorMsg(res, err);
        }
        break;
    }
    dahua.on("error", function (error) {
      console.log("error", error);
    });
  } else {
    ErrorMsg(
      res,
      `${query.status ? query.status : ""} - ${
        !dahua ? "dahua实例未初始化请初始化/init" : null
      }`
    );
  }
  res.status(200);

  function PtzMove(query) {
    return new Promise((resolve, reject) => {
      if (query.directions && query.actions && query.speed) {
        dahua.ptzMove(
          (err) => {
            console.log("PtzMove -> err", err);
            reject(err);
          },
          (res) => {
            resolve(res);
          },
          query.directions,
          query.actions,
          query.speed
        );
      } else {
        reject("传递参数不正确");
      }
    });
  }
});

/**
 * 成功返回消息
 * @param {*} res
 * @param {*} msg
 */
function SuccMsg(res, msg) {
  res.send(Object.assign(json, { code: 1, data: { msg } }));
}

/**
 * 失败返回消息
 * @param {*} res
 * @param {*} msg
 */
function ErrorMsg(res, msg) {
  res.send(Object.assign(json, { code: -1, data: { msg } }));
}

app.use(router);

app.listen(port, () => {
  console.log(`服务启动成功 ${port}`);
});
